package com.hb.trans.mvp.ui.activity


import android.Manifest
import android.annotation.SuppressLint
import android.location.Location
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AlertDialog
import androidx.recyclerview.widget.LinearLayoutManager
import android.view.MenuItem
import android.view.View
import android.view.inputmethod.EditorInfo
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.basiclib.base.BaseActivity
import com.basiclib.utils.hideSoftKeyword
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.bigkoo.pickerview.view.OptionsPickerView
import com.hb.trans.R
import com.hb.trans.bean.City
import com.hb.trans.bean.School
import com.hb.trans.global.ACTIVITY_HOME_REGISTER
import com.hb.trans.global.ACTIVITY_SCHOOL_INFO
import com.hb.trans.mvp.contract.SchoolsContract
import com.hb.trans.mvp.presenter.SchoolsPresenter
import com.hb.trans.mvp.ui.adapter.SchoolAdapter
import com.hb.trans.utils.LocationMgr
import com.jakewharton.rxbinding2.view.clicks
import com.tbruyelle.rxpermissions2.RxPermissions
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_schools.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import javax.inject.Inject

@Route(path = ACTIVITY_HOME_REGISTER)
class SchoolsActivity : BaseActivity(), SchoolsContract.View, OnOptionsSelectListener {
    val SELECT_CITY = 1 //选择市
    val SELECT_DISTRICT = 2 //选择县
    @Inject
    lateinit var mPresenter: SchoolsPresenter
    @Inject
    lateinit var mAdapter: SchoolAdapter
    private var isShowDialog = false
    private var locCity: String? = null //定位市
    private var locProvince: String? = null//定位省
    private var locDistrict: String? = null//定位区县
    private var selectType = -1 //选择类型
    private val cities = mutableListOf(
        City(code = "130100", name = "石家庄市"),
        City(code = "130200", name = "唐山市"),
        City(code = "130300", name = "秦皇岛市"),
        City(code = "130400", name = "邯郸市"),
        City(code = "130500", name = "邢台市"),
        City(code = "130600", name = "保定市"),
        City(code = "130700", name = "张家口市"),
        City(code = "130800", name = "承德市"),
        City(code = "130900", name = "沧州市"),
        City(code = "131000", name = "廊坊市"),
        City(code = "131100", name = "衡水市")
    )

    private var countyMap: MutableMap<String, MutableList<City>>? = null
    private var districtes: MutableList<City>? = null

    var pvOptions: OptionsPickerView<String>? = null

    override fun getContentViewResId(): Int = R.layout.activity_schools

    override fun onActivityInject() {
        AndroidInjection.inject(this)
    }

    override fun attachView(savedInstanceState: Bundle?) {
        mPresenter.attachView(this)
//        EventBus.getDefault().register(this)
//        ImmersionBar.with(this)
//            .statusBarColor(R.color.colorPrimary)
//            .init()
    }

    override fun getPresenter(): SchoolsPresenter? = mPresenter

    override fun initView() {
        setSupportActionBar(schoolToolbar.toolbar)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)
        supportActionBar!!.setHomeAsUpIndicator(R.mipmap.ic_left_arrow)


        schoolRv.apply {
            layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this@SchoolsActivity)
            adapter = mAdapter
        }
        requestLocationPermission()
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            android.R.id.home -> onBackPressed()
        }
        return true
    }

    @SuppressLint("CheckResult")
    private fun requestLocationPermission() {
        val permission = RxPermissions(this)
        permission.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
            .subscribe {
                if (it) {
                    LocationMgr.getInstance(this).initLocation()
                } else {
                    AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("应用需要定位权限或定位未打开")
                        .setPositiveButton("确定") { dialog, _ ->
                            dialog.dismiss()
                        }.show()
                }
            }
    }

    override fun initData() {
    }

    @SuppressLint("CheckResult")
    override fun setListener() {
//        schoolToolbar.backClick()?.subscribe {
//            hideSoftKeyword()
//            finish()
//        }

        tvCity.clicks().subscribe {
            selectType = SELECT_CITY
            showPickView(cities)
        }

        tvCounty.clicks().subscribe {
            selectType = SELECT_DISTRICT
            districtes?.let {
                showPickView(districtes!!)
            }
        }

        mAdapter.setOnItemClickListener { adapter, _, position ->

            ARouter.getInstance()
                .build(ACTIVITY_SCHOOL_INFO)
                .withObject("schoolInfo", adapter.getItem(position) as School)
                .navigation()
        }
        etSchoolName.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftKeyword()
                val temp = v.text.toString().trim()
                if (!temp.isBlank()) {
                    mPresenter.findSchools(temp)
                }
                true
            }
            false
        }

    }

    private fun showPickView(datas: MutableList<City>) {
        hideSoftKeyword()
        pvOptions = OptionsPickerBuilder(this, this)
            .setSelectOptions(0)//设置默认选中项
            .setSubmitText("确定")//确定按钮文字
            .setCancelText("取消")//取消按钮文字
            .setSubCalSize(18)//确定和取消文字大小
            .setTitleSize(20)//标题文字大小
            .setSubmitColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))//确定按钮文字颜色
            .setCancelColor(ContextCompat.getColor(this, R.color.colorPrimaryDark))//取消按钮文字颜色
            .setTitleBgColor(ContextCompat.getColor(this, R.color.white))//标题背景颜色 Night mode
            .setBgColor(ContextCompat.getColor(this, R.color.white))//滚轮背景颜色 Night mode
            .setContentTextSize(18)//滚轮文字大小
            .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
            .setCyclic(false, false, false)//循环与否
            .setOutSideCancelable(false)//点击外部dismiss default true
            .isDialog(false)//是否显示为对话框样式
            .isRestoreItem(true)//切换时是否还原，设置默认选中第一项。
            .build<String>()
        pvOptions!!.setPicker(datas.map { it.name }, null, null)//添加数据源
        pvOptions!!.show(true)
    }

    override fun onOptionsSelect(options1: Int, options2: Int, options3: Int, v: View?) {
        when (selectType) {
            SELECT_CITY -> {
                districtes = null
                val city = cities[options1]
                tvCity.text = city.name
                districtes = countyMap?.get(city.code)
                districtes?.first()?.let {
                    tvCounty.text = it.name
                    mPresenter.getSchools(it.code)
                }
            }
            SELECT_DISTRICT -> {
                districtes?.let {
                    tvCounty.text = districtes!![options1].name
                    mPresenter.getSchools(districtes!![options1].code)
                }
            }
        }
    }

    private fun dismissPickerView() {
        if (pvOptions != null && pvOptions!!.isShowing) {
            pvOptions?.dismiss()
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventLocation(location: Location) {
        mPresenter.getLocationInfo(location)
        LocationMgr.getInstance(this).destory()
    }

    override fun setCurrentLocationCity(province: String, city: String, district: String) {
        this.locCity = city
        this.locProvince = province
        this.locDistrict = district
        getSchools()
    }

    override fun setCounties(counties: MutableMap<String, MutableList<City>>?) {
        this.countyMap = counties
        getSchools()
    }

    private fun getSchools() {
        if (locProvince == null) {

        } else if ("河北省" != locProvince && !isShowDialog) {
            isShowDialog = true
            AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("当前定位不在河北省,请手动选择地区")
                .setCancelable(true)
                .setPositiveButton("确认", null)
                .show()
        } else if ("河北省" == locProvince) {
            cities.find {
                locCity == it.name
            }?.apply {
                districtes = countyMap?.get(code)
                tvCity.text = name
            } ?: setDefaultDistrictes()
            val locdis = districtes?.find {
                locDistrict == it.name
            }?.apply {
                tvCounty.text = name
            }
            locdis?.let {
                mPresenter.getSchools(locdis.code)
            }
        }
    }

    private fun setDefaultDistrictes() {
        districtes = countyMap?.get("130100")
        tvCity.text = "石家庄市"
    }

    override fun setupSchoolData(data: MutableList<School>?) {
        data?.let {
            if (it.size > 0) {
                showDataView()
                mAdapter.setNewData(data)
            } else {
                showNoDataView()
            }
        } ?: showNoDataView()

    }

    private fun showNoDataView() {
        rlNoData.visibility = View.VISIBLE
        schoolRv.visibility = View.GONE
    }

    private fun showDataView() {
        rlNoData.visibility = View.GONE
        schoolRv.visibility = View.VISIBLE
    }


//    override fun onDestroy() {
//        super.onDestroy()
//        EventBus.getDefault().unregister(this)
//        ImmersionBar.with(this).destroy()
//    }
}
